package com.economy.swefunds;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.os.Handler;
import android.util.Log;

public class UrlLoader implements Runnable {

	public static final int CONNECTION_SUCCEDED = 0;
	public static final int CONNECTION_TIMEOUT = 1;
	public static final int CONNECTION_FAILED = 2;
	
	private URL PageUrl = null;
	private Handler CallbackHandler;
	private TagNode Page;
	private HtmlCleaner PageParser;
	
	public UrlLoader(Handler handler) {
		CallbackHandler = handler;
		
		// We need to "clean up" the page to be able to XML-parse it  
    	PageParser = new HtmlCleaner();
    	CleanerProperties props = PageParser.getProperties();
    	props.setAllowHtmlInsideAttributes(true);
    	props.setAllowMultiWordAttributes(true);
    	props.setRecognizeUnicodeChars(true);
    	props.setOmitComments(true);
	}
	
	public void loadUrl(URL url) {
		PageUrl = url;
		Thread thread = new Thread(this);
		thread.start();
	}

	// This is inherited from Runnable. Do not call this directly, use loadUrl instead! 
	public void run() {
		if (CallbackHandler == null)
			return;
		
		if (PageUrl == null) {
			CallbackHandler.sendEmptyMessage(CONNECTION_FAILED);
			return;
		}
		
		URLConnection conn;
		try {
			conn = PageUrl.openConnection();
			conn.setConnectTimeout(25 * 1000); // 25s connection time out
			// TODO: Get real text encoding from page (how?)
			Page = PageParser.clean(new InputStreamReader(conn.getInputStream(), "ISO-8859-1"));
		} catch (SocketTimeoutException e) {
			CallbackHandler.sendEmptyMessage(CONNECTION_TIMEOUT);
			return;
		} catch (IOException e) {
    		Log.e("ERROR", e.getMessage());
    		CallbackHandler.sendEmptyMessage(CONNECTION_FAILED);
    		return;
		}
		
		CallbackHandler.sendEmptyMessage(CONNECTION_SUCCEDED);
	}
	
	public TagNode getPage() {
		if (Page == null)
			Page = new TagNode(null);
		return Page;
	}
	
}
